package com.dragon.modules.yuegou.client.wechat.client.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sgy.ysq.core.web.SystemCode;
import com.sgy.ysq.wx.client.WxTokenClient;
import com.sgy.ysq.wx.client.WxUserClient;
import com.sgy.ysq.wx.model.WXTokenModel;
import com.sgy.ysq.wx.model.WXUserModel;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tech.liuwu.commons.exception.BusinessException;

@Service
public class WxUserClientImpl implements WxUserClient {
    private  Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private WxTokenClient wxTokenClient;

    @Override
    public WXUserModel userInfo(String code, String appid, String secret) {
        WXTokenModel wxTokenModel = wxTokenClient.getGZHToken(code,appid,secret);
        String url = "https://api.weixin.qq.com/sns/userinfo";
        //获取Token 所需参数
        String param = String.format("access_token=%s&openid=%s",wxTokenModel.getAccessToken(),wxTokenModel.getOpenid());
        //http 请求头设置
        HttpClient client = new HttpClient();
        PostMethod method = new PostMethod(url);
        method.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

        //设置参数
        RequestEntity requestEntity = new StringRequestEntity(param);
        method.setRequestEntity(requestEntity);

        try {
            //执行请求
            client.executeMethod(method);

            //返回请求,判断状态
            if (method.getStatusCode() == HttpStatus.SC_OK) {//请求成功,状态200
                String response = method.getResponseBodyAsString();
                response = new String(response.getBytes("ISO-8859-1"), "UTF-8");
                logger.debug("getToken Response:" + response);
                WXUserModel wxUserModel = new WXUserModel();
                //转换成JSON,获取token 并返回
                JSONObject jsonObject = JSON.parseObject(response);
                String openid = jsonObject.getString("openid");
                String city = jsonObject.getString("city");
                String headimgurl = jsonObject.getString("headimgurl");
                String nikename = jsonObject.getString("nickname");
                String sex = jsonObject.getString("sex");
                String province = jsonObject.getString("province");
                String country = jsonObject.getString("country");
                String privilege = jsonObject.getString("privilege");
                String unionid = jsonObject.getString("unionid");
                if (StringUtils.isNotBlank(openid)){
                    wxUserModel.setOpenid(openid);
                    wxUserModel.setCity(city);
                    wxUserModel.setCountry(country);
                    wxUserModel.setHeadimgurl(headimgurl);
                    wxUserModel.setNickname(nikename);
                    wxUserModel.setPrivilege(privilege);
                    wxUserModel.setProvince(province);
                    wxUserModel.setSex(sex);
                    wxUserModel.setUnionid(unionid);
                    return wxUserModel;
                }
                throw new BusinessException(SystemCode.TOKEN_ERROR);
            } else {//请求失败
                throw new Exception("http statusCode:" + String.valueOf(method.getStatusCode()) + "\n"
                        + method.getStatusText() + "\n" + "url:" + method.getURI());
            }
        } catch (Exception e) {
            logger.error(String.format("getToken 异常:%s", e.getMessage()), e);
            throw new BusinessException(SystemCode.TOKEN_ERROR);
        }
    }


}
